package ws.websk.chatEndpoint;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.IOException;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 *
 * @author Jens-Marius Nergård Hansen
 */

@ServerEndpoint("/ws")
public class ChatEndpoint {

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        Set<Session> sessions = session.getOpenSessions();
        System.out.println("onMessage: " + message + "Num of peers: " + sessions.size());

        for(Session s:sessions){
            if(s.isOpen() && !s.equals(session)){
                s.getBasicRemote().sendText(message);
            }
        }
    }

    @OnOpen
    public void onOpen(Session peer){
        System.out.println("Client connected: " + peer.getId());
        //Notify all connected clients that the user has connected
        for(Session s:peer.getOpenSessions()){
            try {
                s.getBasicRemote().sendText("Disconnected: " + peer.getId());
            } catch (IOException ex) {
                Logger.getLogger(ChatEndpoint.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @OnClose
    public void onClose(Session peer){
        System.out.println("Client disconnected:" + peer.getId());
        //Notify all connected clients that the user has disconnected
    }

    @OnError
    public void onError(Session s, Throwable t) {
    }
 }